package com.atguigu.gmall.realtime.dwd.app;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.realtime.common.base.BaseApp;
import com.atguigu.gmall.realtime.common.bean.TableProcessDim;
import com.atguigu.gmall.realtime.common.constant.Constant;
import com.atguigu.gmall.realtime.common.util.FlinkSourceUtil;
import com.atguigu.gmall.realtime.common.util.HBaseUtil;
import com.atguigu.gmall.realtime.dwd.function.DimSinkFunction;
import com.atguigu.gmall.realtime.dwd.function.TableProcessFunction;
import com.ververica.cdc.connectors.mysql.source.MySqlSource;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.state.MapStateDescriptor;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.BroadcastConnectedStream;
import org.apache.flink.streaming.api.datastream.BroadcastStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.util.Collector;
import org.apache.hadoop.hbase.client.Connection;

public class Dimapp extends BaseApp {
    public static void main(String[] args) {
        new Dimapp().start(10001,4,"dim_app_group", Constant.TOPIC_DB);
    }

    @Override
    public void handle(StreamExecutionEnvironment env, DataStreamSource<String> kafkaStrDS) {
        // TODO 4. 对流中数据进行类型转换并进行简单的ETL jsonStr -> jsonObject
        SingleOutputStreamOperator<JSONObject> jsonObjDS = etl(kafkaStrDS);
        // TODO 5. 使用FlinkCDC从配置表中读取配置信息
        SingleOutputStreamOperator<TableProcessDim> tpDS = readTableProcess(env);
        // TODO 7. 在广播配置信息前，根据配置流中的配置在HBase中执行建表或者删除操作
        tpDS = creatHBaseTable(tpDS);
        // TODO 8. 关联主流业务数据以及广播流配置信息 -- connect
        SingleOutputStreamOperator<Tuple2<JSONObject, TableProcessDim>> dimDS = connect(tpDS, jsonObjDS);
        // TODO 11. 将维度数据同步到HBase对应的表中
        dimDS.print();
        dimDS.addSink(new DimSinkFunction());
        //dimDS.sinkTo();
    }

    private static SingleOutputStreamOperator<Tuple2<JSONObject, TableProcessDim>> connect(SingleOutputStreamOperator<TableProcessDim> tpDS, SingleOutputStreamOperator<JSONObject> jsonObjDS) {
        //TODO 8. 广播配置流 -- broadcast
        MapStateDescriptor<String, TableProcessDim> mapStateDescriptor
                = new MapStateDescriptor<String, TableProcessDim>("mapStateDescriptor", String.class, TableProcessDim.class);
        BroadcastStream<TableProcessDim> broadcastDS = tpDS.broadcast(mapStateDescriptor);
        // TODO 9. 关联主流业务数据以及广播流配置信息 -- connect
        BroadcastConnectedStream<JSONObject, TableProcessDim> connectDS = jsonObjDS.connect(broadcastDS);
        // TODO 10. 对关联后的数据进行处理 -- process
        SingleOutputStreamOperator<Tuple2<JSONObject, TableProcessDim>> dimDS = connectDS.process(new TableProcessFunction(mapStateDescriptor));
        return dimDS;
    }

    private static SingleOutputStreamOperator<TableProcessDim> readTableProcess(StreamExecutionEnvironment env) {
        MySqlSource<String> mysqlSource = FlinkSourceUtil.getMysqlSource("gmall0221_config", "table_process_dim");
        // 5.2 读取数据 封装为流
        DataStreamSource<String> mysqlStrDS = env.fromSource(mysqlSource, WatermarkStrategy.noWatermarks(), "mysql_source");
        // TODO 6. 对flinkCDC读取到数据进行类型转换 jsonStr -> 实体类对象
        SingleOutputStreamOperator<TableProcessDim> tpDS =  mysqlStrDS.map(
                    new MapFunction<String, TableProcessDim>() {
                        @Override
                        public TableProcessDim map(String jsonStr) throws Exception {
                            JSONObject jsonObj = JSON.parseObject(jsonStr);
                            TableProcessDim tableProcessDim = null;
                            String op = jsonObj.getString("op");
                            if ("d".equals(op)) {
                                // 说明从配置表中删除了一条信息 ， 需要从before属性中获取对应配置信息
                                tableProcessDim = jsonObj.getObject("before", TableProcessDim.class);
                            } else {
                                // 说明从配置表中增|删|查一条信息 ， 需要从after属性中获取对应配置信息
                                tableProcessDim = jsonObj.getObject("after", TableProcessDim.class);
                            }
                            tableProcessDim.setOp(op);
                            return tableProcessDim;
                        }
                    });
        return tpDS;
    }

    private static SingleOutputStreamOperator<TableProcessDim> creatHBaseTable(SingleOutputStreamOperator<TableProcessDim> tpDS) {
        SingleOutputStreamOperator<TableProcessDim> map = tpDS.map(
                new RichMapFunction<TableProcessDim, TableProcessDim>() {
                    Connection hBaseConnection;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        hBaseConnection = HBaseUtil.getHBaseConnection();
                    }

                    @Override
                    public TableProcessDim map(TableProcessDim tableProcessDim) throws Exception {
                        String op = tableProcessDim.getOp();

                        String sinkTable = tableProcessDim.getSinkTable();
                        String[] families = tableProcessDim.getSinkFamily().split(",");
                        if ("c".equals(op) || "r".equals(op)) {
                            HBaseUtil.createHBaseTable(hBaseConnection, Constant.HBASE_NAMESPACE, sinkTable, families);
                        } else if ("d".equals(op)) {
                            HBaseUtil.dropHBaseTable(hBaseConnection, Constant.HBASE_NAMESPACE, sinkTable);
                        } else {
                            HBaseUtil.createHBaseTable(hBaseConnection, Constant.HBASE_NAMESPACE, sinkTable, families);
                            HBaseUtil.dropHBaseTable(hBaseConnection, Constant.HBASE_NAMESPACE, sinkTable);

                        }
                        return tableProcessDim;
                    }
                }
        ).setParallelism(1);
        return tpDS;
    }

    private static SingleOutputStreamOperator<JSONObject> etl(DataStreamSource<String> kafkaStrDS) {
        SingleOutputStreamOperator<JSONObject> jsonObjDS = kafkaStrDS.process(
                new ProcessFunction<String, JSONObject>() {
                    @Override
                    public void processElement(String jsonStr, ProcessFunction<String, JSONObject>.Context context, Collector<JSONObject> collector) throws Exception {
                        JSONObject jsonObject = JSON.parseObject(jsonStr);
                        //对脏数据处理（根据业务需求来）
                        String db = jsonObject.getString("database");
                        String type = jsonObject.getString("type");
                        String data = jsonObject.getString("data");
                        if("gmall0224".equals(db)
                                && ("insert".equals(type)
                                ||  "update".equals(type)
                                ||  "delete".equals(type)
                                ||  "bootstrap-insert".equals(type))
                                && data != null
                                && data.length() > 2){
                            collector.collect(jsonObject);
                        }
                    }
                }
        );
        return jsonObjDS;
    }
}
